﻿#region Copyright(C)  2018 FI Ltd. All rights reserved.
// ==================================================================================================
// Copyright(C)  2018 FI Ltd. All rights reserved.
//
// SYSTEM NAME	:   FI.Net Application Framework
// COMPONENT ID :   FI.Core.Mvc
// COMPONENT DESC:  Core components integrated with ASP.NET MVC
//
// CREATED DATE/BY:  19 Dec 2018 / Tian Mi
//
// REVISION HISTORY:	
// DATE/BY			SR#/CS/PM#/OTHERS		DESCRIPTION OF CHANGE
// ==================================================================================================
#endregion
using FI.Core.IoC;
using FI.Core.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Routing;

namespace FI.Core.Mvc
{
    /// <summary>
    /// A custom controller activator, which uses specified service locator for controller activation.
    /// </summary>
    public class ServiceLocatableControllerActivator: IControllerActivator
    {
         #region Properties
        /// <summary>
        /// Gets the service locator.
        /// </summary>
        public IServiceLocator ServiceLocator { get; private set; }
        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceLocatableControllerActivator"/> class.
        /// </summary>
        /// <param name="serviceLocatorName">Name of the service locator.</param>
        public ServiceLocatableControllerActivator(string serviceLocatorName = "")
        {
            if (string.IsNullOrEmpty(serviceLocatorName))
            {
                this.ServiceLocator = ServiceLocatorFactory.GetServiceLocator();
            }
            else
            {
                this.ServiceLocator = ServiceLocatorFactory.GetServiceLocator(serviceLocatorName);
            }
        }
        #endregion

        /// <summary>
        /// Creates the specified request context.
        /// </summary>
        /// <param name="requestContext">The request context.</param>
        /// <param name="controllerType">Type of the controller.</param>
        /// <returns>The activated controller instance.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public IController Create(RequestContext requestContext, Type controllerType)
        {
            Guard.ArgumentNotNull(requestContext, "requestContext");
            Guard.ArgumentNotNull(controllerType, "controllerType");
            return this.ServiceLocator.GetService(controllerType) as IController;
        }
    }
}
